package com.example.utils;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/email")
public class Email {

    @GetMapping("/send")
    public void sendEmail(@RequestParam("email") String email, @RequestParam("text") String text) {
        // 发件人电子邮箱
        String from = "1298983790@qq.com";

        //生成的授权码
        String password = "onoanqcavdpeghcb";

        // 指定发送邮件的主机为 smtp.qq.com
        String host = "smtp.qq.com";  //QQ 邮件服务器

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        properties.put("mail.smtp.auth", "true");
        // 获取默认session对象
        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password); // 发件人邮件用户名、授权码
            }
        });

        // 设置debug模式便于调试:
        session.setDebug(true);

        try{
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(email));

            // Set Subject: 头部头字段
            message.setSubject("这是注册的验证码，仅供个人，不可转发给他人，有效期为30秒","UTF-8");

            // 设置消息体
            message.setText("验证码："+text,"UTF-8");

            // 发送消息
            Transport.send(message);

            //发送完成后控制台打印输出
            System.out.println("Sent message successfully....");
        }catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }




}
